import os
import markdown
from django.utils import timezone
from django.contrib.auth.models import User
from algorithm.models import (
    UserComprehensiveLevel,
    UserTagMastery,
    UserProblemRecommendation,
)
from recommendation.models import SolvedProblem
from problems.models import Problem
from tag.models import Tag
from recommendation_pool.models import UserRecommendationPool,UserUndoPool
from django.db.models import F
from django.utils import timezone
from datetime import datetime
def export_user_data_to_md(user_id):
    try:
        user = User.objects.get(id=user_id)

        # 使用系统的本地时间并插入自定义间隔符
        timestamp = datetime.now().strftime('%Y%m%d_%H-%M-%S')
        filename = f"{user.username}_data_{timestamp}.md"

        filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs", filename)

        # Initialize markdown content
        md_content = []

        # Section for UserComprehensiveLevel
        md_content.append("# User Comprehensive Level")
        user_comprehensive_level = UserComprehensiveLevel.objects.filter(user=user).first()
        if user_comprehensive_level:
            md_content.append("| User ID | User Name | Tag Solving Level | User Level |")
            md_content.append("|---------|-----------|-------------------|------------|")
            md_content.append(f"| {user.id} | {user.username} | {user_comprehensive_level.tag_solving_level:.2f} | {user_comprehensive_level.user_level:.2f} |")
        else:
            md_content.append("No data available.")

        # Section for SolvedProblem
        md_content.append("\n# Solved Problems")
        md_content.append("| User ID | User Name | Problem Number |")
        md_content.append("|---------|-----------|----------------|")
        solved_problems = SolvedProblem.objects.filter(user=user).select_related('problem').annotate(
            problem_number=F('problem__problem_number'))
        for solved in solved_problems:
            md_content.append(f"| {user.id} | {user.username} | {solved.problem_number} |")
        if not solved_problems:
            md_content.append("No data available.")

        # Section for UserTagMastery
        md_content.append("\n# User Tag Mastery")
        md_content.append("| User ID | User Name | Tag Name | Mastery Score | Mastery Level | Recommendation Score |")
        md_content.append("|---------|-----------|----------|---------------|---------------|----------------------|")
        tag_masteries = UserTagMastery.objects.filter(user=user).select_related('tag').annotate(
            tag_name=F('tag__tag_name'))
        for mastery in tag_masteries:
            md_content.append(f"| {user.id} | {user.username} | {mastery.tag_name} | {mastery.mastery_score:.2f} | {mastery.mastery_level:.2f} | {mastery.recommendation_score:.2f} |")
        if not tag_masteries:
            md_content.append("No data available.")

        # Section for UserRecommendationPool
        md_content.append("\n# User Recommendation Pool")
        md_content.append("| User ID | User Name | Problem Number |")
        md_content.append("|---------|-----------|----------------|")
        recommendation_pool = UserRecommendationPool.objects.filter(user=user).select_related('problem').annotate(
            problem_number=F('problem__problem_number'))
        for recommendation in recommendation_pool:
            md_content.append(f"| {user.id} | {user.username} | {recommendation.problem_number} |")
        if not recommendation_pool:
            md_content.append("No data available.")

        # Section for UserUndoPool
        md_content.append("\n# User Undo Pool")
        md_content.append("| User ID | User Name | Problem Number | Timestamp |")
        md_content.append("|---------|-----------|----------------|-----------|")
        undo_pool = UserUndoPool.objects.filter(user=user).select_related('problem').annotate(
            problem_number=F('problem__problem_number'))
        for undo in undo_pool:
            md_content.append(f"| {user.id} | {user.username} | {undo.problem_number} | {undo.timestamp.strftime('%Y-%m-%d %H:%M:%S')} |")
        if not undo_pool:
            md_content.append("No data available.")

        # Section for UserProblemRecommendation
        md_content.append("\n# User Problem Recommendation")
        md_content.append("| User ID | User Name | Problem Number | Recommendation Score |")
        md_content.append("|---------|-----------|----------------|----------------------|")
        problem_recommendations = UserProblemRecommendation.objects.filter(user=user).select_related('problem').annotate(
            problem_number=F('problem__problem_number'))
        for recommendation in problem_recommendations:
            md_content.append(f"| {user.id} | {user.username} | {recommendation.problem_number} | {recommendation.recommendation_score:.2f} |")
        if not problem_recommendations:
            md_content.append("No data available.")

        # Write to markdown file
        with open(filepath, "w", encoding="utf-8") as md_file:
            md_file.write("\n".join(md_content))

        print(f"Data successfully exported to {filepath}")

    except User.DoesNotExist:
        print(f"User with ID {user_id} does not exist.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")
